package myTest;

import info.monitorenter.cpdetector.io.ASCIIDetector;
import info.monitorenter.cpdetector.io.CodepageDetectorProxy;
import info.monitorenter.cpdetector.io.JChardetFacade;
import info.monitorenter.cpdetector.io.ParsingDetector;
import info.monitorenter.cpdetector.io.UnicodeDetector;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

public class GbkToUtf {
	private static Map<String, String> convertTypeMap = new HashMap<String, String>();
	private static String fromPath = "D:\\work\\fromPath\\";
	private static String toPath = "D:\\work\\toPath\\";

	public static void main(String[] args) {
		convertTypeMap.put("java", "java");
		//convertTypeMap.put("jsp", "jsp");
		File file = new File(fromPath);
		/*System.out.println(isConvertType("ssss.java"));
		System.out.println(isConvertType("ssss.jsp"));
		System.out.println(isConvertType("ssss.jkp"));*/
		try {
			showAllFiles(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void showAllFiles(File dir) throws Exception {
		File[] fs = dir.listFiles();
		for (int i = 0; i < fs.length; i++) {
			if (fs[i].isDirectory()) {
				try {
					showAllFiles(fs[i]);
				} catch (Exception e) {
				}
			}else{
				File file = fs[i];
				if(isConvertType(file.getName())&&isGbk(file)){
					toUtf(file);
				}
			}
		}
	}

	private static void toUtf(File file) {
		try {
			BufferedReader br = new BufferedReader(
					new InputStreamReader(new FileInputStream(file), Charset.forName("GBK")));
			File fileTo = new File(file.getAbsolutePath().replace(fromPath, toPath));
			createFile(fileTo);
			System.out.println(fileTo.getAbsolutePath());
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileTo), Charset.forName("UTF-8")));
			String str;
			while((str = br.readLine()) != null){
				bw.write(str);
				bw.newLine();
			}
			br.close();
            bw.flush();
            bw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
		}
	}
	/*private static boolean isGbk(File file){
		if(file.getName().contains("KtwMsgSender")){
			System.out.println(file.getName());
		}
		if(file.getName().contains("LimitBusiness")){
			System.out.println(file.getName());
		}
		BufferedInputStream bin = null;
		try {
			bin = new BufferedInputStream(  
				    new FileInputStream(file));
			 int p = (bin.read() << 8) + bin.read();  
			    String code = null;  
			    switch (p) {  
			        case 0xefbb:  
			            code = "UTF-8";  
			            break;  
			        case 0xfffe:  
			            code = "Unicode";  
			            break;  
			        case 0xfeff:  
			            code = "UTF-16BE";  
			            break;  
			        default:  
			            code = "GBK";  
			    }  
			    if(code.equals("GBK")){
			    	return true;
			    }
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				bin.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}*/
	private static boolean isConvertType(String s) {
		String[] strs = s.split("\\.");
        return convertTypeMap.containsKey(strs[1]);
    }
	
	public static boolean createFile(File file) throws IOException {  
        if(! file.exists()) {  
            makeDir(file.getParentFile());  
        }  
        return file.createNewFile();  
    }  
      
    public static void makeDir(File dir) {  
        if(! dir.getParentFile().exists()) {  
            makeDir(dir.getParentFile());  
        }  
        dir.mkdir();  
    }  
    
    public static boolean isGbk(File file) { 
    	  /** 
    	   * <pre> 
    	   * 1、cpDetector内置了一些常用的探测实现类,这些探测实现类的实例可以通过add方法加进来,如:ParsingDetector、 JChardetFacade、ASCIIDetector、UnicodeDetector. 
    	   * 2、detector按照“谁最先返回非空的探测结果,就以该结果为准”的原则. 
    	   * 3、cpDetector是基于统计学原理的,不保证完全正确. 
    	   * </pre> 
    	   */ 
    	  CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance(); 
    	  detector.add(new ParsingDetector(false)); 
    	  detector.add(JChardetFacade.getInstance());// 需要第三方JAR包:antlr.jar、chardet.jar. 
    	  detector.add(ASCIIDetector.getInstance()); 
    	  detector.add(UnicodeDetector.getInstance()); 
    	  Charset charset = null; 
    	  try { 
    	   charset = detector.detectCodepage(file.toURI().toURL()); 
    	  } catch (Exception e) { 
    	  } 

    	  String charsetName = "GBK"; 
    	  if (charset != null) { 
    	   if (charset.name().equals("US-ASCII")) { 
    	    charsetName = "ISO-8859-1"; 
    	   } else if (charset.name().startsWith("UTF")) { 
    	    charsetName = charset.name();// 例如:UTF-8,UTF-16BE. 
    	   } 
    	  } 
    	  if(charsetName.equals("GBK")){
    		  return true;
    	  }
    	  return false; 
    	} 
}
